package eraserhead.controller;

import client.ServerAccess;
import eraserhead.boundary.CreateEventForm;
import eraserhead.boundary.DecisionGUI;
import eraserhead.boundary.WarningWindow;
import eraserhead.entity.ClosedDecision;
import eraserhead.entity.Decision;
import eraserhead.entity.OpenDecision;
import eraserhead.xml.request.CreateOpenRequest;

/**
 * Gets the information from the GUI and create request to send to server
 * @author zhaolongli
 * @author Quanquan
 */
public class CreateEventController {

	//GUI to get information from
	CreateEventForm view;

	/**
	 * Creates a new {@link CreateEventController}
	 * @param view {@link CreateEventForm} to get information from
	 */
	public CreateEventController(CreateEventForm view){
		this.view = view;
	}

	public void process(){

		// just for testing purpose

		// number of user
		/*int numN = 3;
		//number of rounds
		int numM = 3;
		//Question
		String question = "testing";
		//status of event
		String type = "open";
		// Moderator's username
		String moderator = "";
		// Moderator's optional password
		String password = "";
		// List of choices (closed event only)
		String[] choices = new String[numN];

		// just a test.......
		/*
		String xmlString = Message.requestHeader() + "<createRequest type='" + type + "' " +
				"question='" + question + "' " +
				"numChoices='" + numN + "' " + 
				"numRounds = '" + numM + "'> " +
			    "<choice value = 'choice1'   index='1'/>"+
			    "<user   name='Zhaolong Li' />"+
			    "</createRequest>"+
			    "</request>";


		Message req = new Message (xmlString);
		ServerAccessManager.getAccess().sendRequest(req);
		 */


		if (view.getQuestion().length() == 0) {
			WarningWindow.giveWarning(view, "Question cannot be empty");
			return;
		}

		Decision d;
		if (view.getIsOpen()) {
			d = new OpenDecision(view.getNumRounds(), view.getNumUsers());
		} else {
			d = new ClosedDecision(view.getNumRounds(), view.getNumUsers());
		}
		d.setQuestion(view.getQuestion());
		d.userJoin(view.getModerator());
		//LoginForm lf = LoginForm.getInstance(d);
		//lf.setVisible(true);
		view.dispose();
		DecisionGUI dg = DecisionGUI.getInstance(d);
		new UserController(d, dg.getChoicePanel()).process();
		dg.setVisible(true);
		ServerAccess sa = ServerAccessManager.getAccess();
		if (view.getIsOpen()) {
			CreateOpenRequest.send(sa, view.getQuestion(), view.getNumUsers(), view.getNumRounds(), 
					view.getModerator().getName(), view.getModerator().getPassword());
		} else {
			//d.setFormSent(false);
			dg.setEventIDInstruction();
		}
		view.dispose();
	}

}
